package com.iris.live.services.services.impl;

import com.iris.live.services.data.models.销货单位表Model;
import com.iris.live.services.data.repositories.销货单位表Repository;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.SalesUnitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author: luojie
 * date: 2017/12/15 11:22
 * 财务对接模块 销货单位业务层
 */
@Service
public class SalesUnitImpl implements SalesUnitService {

    private static Logger logger = LoggerFactory.getLogger(SalesUnitImpl.class);
    @Autowired
    private 销货单位表Repository salesUnitRepository;

    /**
     * 查询销货单位
     *
     * @return
     */
    @Override
    public ResultData getSalesUnit(String permit) {
        List resultList = new ArrayList<>();
        销货单位表Model model = salesUnitRepository.selectByPermit(permit);
        if (model == null) {
            Map map = new HashMap();
            map.put("销货单位", "");
            map.put("地址", "");
            map.put("电话", "");
            map.put("开户行", "");
            map.put("账号", "");
            map.put("纳税人识别号", "");
            resultList.add(map);
        } else {
            resultList.add(model);
        }
        return new ResultData("true", "查询成功", new PageData(resultList, resultList.size()));
    }

    /**
     * 新增或修改销货单位
     *
     * @param permit
     * @param user
     * @param salesUnit
     * @return
     */
    @Transactional
    @Override
    public ResultData updateSalesUnit(String permit, String user, 销货单位表Model salesUnit) {
        try {
            销货单位表Model model = salesUnitRepository.selectByPermit(permit);
            salesUnit.set许可(permit);
            salesUnit.set更新账号(user);
            salesUnit.set更新时间(new Timestamp(System.currentTimeMillis()));
            if (model == null) {
                salesUnit.set创建日期(new Timestamp(System.currentTimeMillis()));
                salesUnitRepository.save(salesUnit);
            } else {
                salesUnit.set编号(model.get编号());
                salesUnit.set创建日期(model.get创建日期());
                salesUnitRepository.saveAndFlush(salesUnit);
            }
        } catch (Exception e) {
            logger.error("销货单位保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", "保存失败");
        }
        return new ResultData("true", "保存成功");
    }
}